package com.cutter.mobile;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.net.URI;
import java.net.URISyntaxException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
//import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;



public class splitfile extends Activity {
	
	protected static final int REQUEST_CODE_PICK_FILE_OR_DIRECTORY = 1;
	String Activefilename;
	String Destfolder;
	String ZSPFilename;
	TextView FileParts;
	Spinner ChunkSize;
	int CValue;
	int FParts;
	int Frames;
	String MD5File, Destfile;
	String ffName;
	ArrayAdapter<ChunkValue> adapter;
	MenuInflater inflater;
	MenuItem mnuSendMail, mnuTestBuild, mnuRepeatSplit;
	Button StartButton;
	TextView File1;
	public static final String PREFS_NAME = "CutterMobilePrefs";
	
	private Editable YourName;
	private Editable YourMail;
	private Editable DestMail;
	private ProgressDialog pd;
	private boolean SplitDone = false;
     
//	public Spinner ChunkSize = (Spinner) findViewById(R.id.Spinner01);
	
	public static String getMd5Hash(String input) {
        try     {
                MessageDigest md = MessageDigest.getInstance("MD5");
                byte[] messageDigest = md.digest(input.getBytes());
                BigInteger number = new BigInteger(1,messageDigest);
                String md5 = number.toString(16);
           
                while (md5.length() < 32)
                        md5 = "0" + md5;
           
                return md5;
        } catch(NoSuchAlgorithmException e) {
                //Log.e("MD5", e.getMessage());
                return null;
        }
}

	
	public static String getMd5FileHash(File input) throws NoSuchAlgorithmException, IOException {
            MessageDigest md = MessageDigest.getInstance("MD5");
        	InputStream is = new FileInputStream(input);
        	byte[] buffer = new byte[8192];
        	int read = 0;       	
        	while( (read = is.read(buffer)) > 0) {
        		md.update(buffer, 0, read);
        	}		
        		byte[] md5sum = md.digest();
        		BigInteger bigInt = new BigInteger(1, md5sum);
        		String output = bigInt.toString(16);
			return output;
		
	}	
	@Override
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.splitfile);
        
        // Load UI text
        FileParts = (TextView) findViewById(R.id.TextView05);		
        FileParts.setText(getText(R.string.filepartszero));
        TextView File1 = (TextView) findViewById(R.id.TextView01);
        TextView File2 = (TextView) findViewById(R.id.TextView03);
        TextView File3 = (TextView) findViewById(R.id.TextView02);
        File1.setText(getText(R.string.filenamezero));
        File2.setText(getText(R.string.filesizezero));
        File3.setText(getText(R.string.md5zero));
        
        TextView menuhint = (TextView) findViewById(R.id.pressmenuline);
        menuhint.setVisibility(View.GONE);
        
        final ChunkValue items[] = new ChunkValue[16];        
        items[0] = new ChunkValue( "100 KB",100000 );
        items[1] = new ChunkValue( "250 KB",250000 );
        items[2] = new ChunkValue( "500 KB",500000 );
        items[3] = new ChunkValue( "750 KB",750000 );
        items[4] = new ChunkValue( "1 MB",  1000000 );
        items[5] = new ChunkValue( "2 MB",  2000000 );
        items[6] = new ChunkValue( "4 MB",  4000000 );
        items[7] = new ChunkValue( "5 MB",  5000000 );
        items[8] = new ChunkValue( "8 MB",  8000000 );
        items[9] = new ChunkValue( "16 MB", 16000000 );
        items[10] = new ChunkValue( "32 MB", 32000000 );
        items[11] = new ChunkValue( "64 MB", 64000000 );
        items[12] = new ChunkValue( "128 MB",128000000 );
        items[13] = new ChunkValue( "256 MB",256000000 );
        items[14] = new ChunkValue( "512 MB",512000000 );
        items[15] = new ChunkValue( "1 GB",  1000000000 );
        
		adapter = new ArrayAdapter<ChunkValue>(getBaseContext(), android.R.layout.simple_spinner_item, items);        
    	adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);                   
    	ChunkSize = (Spinner) findViewById(R.id.Spinner01);
    	//ChunkSize.setAdapter(adapter);         
    	ChunkSize.setEnabled(false);    	
    	//ChunkSize.setSelection(-1);  
    	Activefilename = "";
        Button ProceedBut = (Button) findViewById(R.id.Button01);
        ProceedBut.setText(getText(R.string.openfilebut));
        ProceedBut.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
            	Intent intent = new Intent("org.openintents.action.PICK_FILE"); 
            	intent.putExtra("org.openintents.extra.TITLE", getString(R.string.selfiledialogtitle));
        		intent.putExtra("org.openintents.extra.BUTTON_TEXT", getString(R.string.selfiledialogbut));        		
        		startActivityForResult(intent, REQUEST_CODE_PICK_FILE_OR_DIRECTORY);
            }
        });
        
        StartButton = (Button) findViewById(R.id.Button02);
        StartButton.setEnabled(false);
        StartButton.setText(getText(R.string.prooceedbut));
        StartButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				
				final File file = new File(Activefilename);
				String parentPath = file.getParent();
				final String DestPath = parentPath+"/Cutter Output ("+file.getName()+")/";
				Destfolder=DestPath;
				SplitDone=false;
				new File(DestPath).mkdirs();
				pd = new ProgressDialog(splitfile.this);
				pd.setTitle("Cutter is splitting a file");
				pd.setIndeterminate(false);
				pd.setMax(Frames);
				pd.setCancelable(false);
				pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
				pd.show();
				SplitFileTask task = new SplitFileTask();
				
				task.execute(Activefilename, Integer.toString(CValue), DestPath);
	            
					
				//Toast.makeText(getBaseContext(), DestPath, Toast.LENGTH_LONG).show();
				//new File("/sdcard/test/").mkdirs();
				
			}
		});
        
        ChunkSize.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                    public void onNothingSelected(AdapterView<?> parent) {
                    }
    				@Override
    				public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
    					if (Activefilename != "") {
    						ChunkValue d = items[arg2];
    						CValue = d.getValue();
    						//int cf = CalcParts(CValue);
    						Frames = CalcFrames(Activefilename, CValue);
    						String tt = (String) getText(R.string.fileparts);
    						String tc = "";
    						tc = String.format(tt, Frames);
    						FileParts.setText(tc);
    							//	"File parts being created: "+cf);
    					}
    	            }
                }
            );         
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		
        inflater = getMenuInflater();        
        inflater.inflate(R.menu.splitmenu, menu);
        mnuSendMail = menu.findItem(R.id.sendmail)
        .setTitle(getText(R.string.sendpartsmail))
		.setEnabled(false);
        
		mnuTestBuild = menu.findItem(R.id.testjoin)
		.setTitle(getText(R.string.testrebuildbut))
		.setEnabled(false);
		
		mnuRepeatSplit = menu.findItem(R.id.repeatsplit)
		.setTitle(getText(R.string.repeatsplitbut))
		.setEnabled(false);
		
		return true;
    }
	
	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		if (SplitDone) {
			File ffile = new File(Activefilename);
			String foo = ffile.getName();
			foo = foo.substring(0, foo.lastIndexOf('.'));        
			ffName = Destfolder+foo;        
			mnuSendMail.setEnabled(true);
			mnuTestBuild.setEnabled(true);
			mnuRepeatSplit.setEnabled(true);
			return true;
		} else {
			mnuSendMail.setEnabled(false);
			mnuTestBuild.setEnabled(false);
			mnuRepeatSplit.setEnabled(false);
			return false;
		}
    }
    @Override
	public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
        case R.id.sendmail:
        	LayoutInflater factory = LayoutInflater.from(splitfile.this);
            final View textEntryView = factory.inflate(R.layout.mailentry, null);
         	final EditText T1 = (EditText) textEntryView.findViewById(R.id.EditText01);
        	final EditText T2 = (EditText) textEntryView.findViewById(R.id.EditText02);
        	final EditText T3 = (EditText) textEntryView.findViewById(R.id.EditText03);
        	
        	String sendname,sendmail,recpmail;
        	SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
        	final SharedPreferences.Editor editor = settings.edit();
        	
        	sendname = settings.getString("sendername", "");
        	sendmail = settings.getString("sendermail", "");
        	recpmail = settings.getString("recpmail", "");
        	T1.setText(sendname);
        	T2.setText(sendmail);
        	T3.setText(recpmail);
            AlertDialog ad = new AlertDialog.Builder(splitfile.this)
                //.setIcon(R.drawable.alert_dialog_icon)
                .setTitle(getText(R.string.mailcompose))
                .setView(textEntryView)	            
                .setPositiveButton(getText(R.string.mailsendbut), new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                    	YourName = T1.getText();	            			            			
            			YourMail = T2.getText();
            			DestMail = T3.getText(); 
            			editor.putString("sendername", YourName.toString());
        			    editor.putString("sendermail", YourMail.toString());
        			    editor.putString("recpmail", DestMail.toString());
        			    editor.commit();
        			    
                    	pd = new ProgressDialog(splitfile.this);
            			pd.setTitle(R.string.mailprogress);
            			pd.setIndeterminate(false);
            			pd.setMax(Frames);
            			pd.setCancelable(false);
            			pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            			pd.show();
            			            			
            			SendMail task = new SendMail();
        				task.execute(ffName,Integer.toString(Frames), Destfolder);
                    }
                })
                .setNegativeButton(getText(R.string.cancelbut), new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {

                        /* User clicked cancel so do some stuff */
                    }
                })
                .create();
            ad.show();
        return true;
        
        case R.id.testjoin:
        	String ffName = ZSPFilename; //="/sdcard/download/Cutter_Output_(help.pdf)/help.pdf.zsp";
			String Destfold = Destfolder; //="/sdcard/download/Cutter_Output_(help.pdf)/";
			File zspFile = new File(ffName);
			String tit = zspFile.getName();
			
			String tt = (String) getText(R.string.testrebuildtitle);
			String tc = "";
			tc = String.format(tt, tit);
			
			
			pd = new ProgressDialog(splitfile.this);
			pd.setTitle(tc);
			pd.setIndeterminate(true);
			pd.setCancelable(true);
			pd.show();
			String foo = ffName;
			foo = foo.substring(0, foo.lastIndexOf('.'));
			Destfile=foo;
			MergeFileTask doMerge = new MergeFileTask();
			doMerge.execute(ffName, Destfold, foo);
            
            return true;
        case R.id.repeatsplit:
            RepeatSplitMessageBox();
            return true;
        /*case R.id.getmd5menu:
            String dFile=DestPath+"/"+OrigFile;
            String md5sum="";
            try {
				md5sum = getMd5FileHash(new File(dFile));
			} catch (NoSuchAlgorithmException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} finally {
				Toast.makeText(mergefiles.this, md5sum, Toast.LENGTH_LONG).show();
			}
            
            return true;*/
        default:
            return super.onOptionsItemSelected(item);
        }
    }
	@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		
			switch (requestCode) {
			case REQUEST_CODE_PICK_FILE_OR_DIRECTORY:
				if (resultCode == RESULT_OK && data != null) {
					try {
						Activefilename = new URI(data.getDataString()).getPath().toString();
					} catch (URISyntaxException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
					
					if (Activefilename != null) {
						// Get rid of URI prefix:
						/*if (Activefilename.startsWith("file://")) {
						Activefilename = Activefilename.substring(7);
					}*/
						Button StartButton = (Button) findViewById(R.id.Button02);
				        StartButton.setEnabled(true);				        
						File1 = (TextView) findViewById(R.id.TextView01);
						TextView FileMD5 = (TextView) findViewById(R.id.TextView02);
						TextView FileSizeT = (TextView) findViewById(R.id.TextView03);
						String fn = (String) getText(R.string.filename);
						File1.setText(String.format(fn, Activefilename));

						File f = new File(Activefilename);
						long fsize = f.length();
						String files = (String) getText(R.string.filesize);
						FileSizeT.setText(String.format(files, fsize));
						try {
							String md5val = (String) getText(R.string.md5value);
							MD5File = getMd5FileHash(f);
							FileMD5.setText(String.format(md5val, MD5File));
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (NoSuchAlgorithmException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} finally {
							//FileParts.setText("File parts being created: "+CalcFrames(Activefilename, 100000));
							ChunkSize.setAdapter(adapter);
							ChunkSize.setEnabled(true);
						}
					}		
				}
				break;
			}	
		}
	
	

	public int CalcFrames(String fname, int csize){
		int Chunks = 0;
		int spare = 0;
		File f = new File(fname);
		long fsize = 0;
		try {
			fsize = f.length();
		} finally {
			Chunks = (int) (fsize / csize);
			spare = (int) (fsize % csize);
			if (spare != 0) {
				Chunks++;
			}
		}
		return Chunks;
	}
	
	
	public int MessageBox(String Text, String Title, String OKCaption, String CancelCaption, int msgMode) {
		AlertDialog.Builder alt_bld = new AlertDialog.Builder(this);
		alt_bld.setMessage(Text);
		alt_bld.setCancelable(false);
		alt_bld.setPositiveButton(OKCaption, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {
				
		}
		});
		
		if (CancelCaption != "") {
			alt_bld.setNegativeButton(CancelCaption, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {
				//  Action for 'NO' Button
			dialog.cancel();
			}
			});
		}
		
		AlertDialog alert = alt_bld.create();
		// Title for AlertDialog
		alert.setTitle(Title);
		// Icon for AlertDialog
		switch (msgMode) {
			case 1: alert.setIcon(R.drawable.alert48);
			case 2: alert.setIcon(R.drawable.close48);
			case 3: alert.setIcon(R.drawable.info48);
		}
		//alert.setIcon(R.drawable.icon);
		alert.show();
				
		return 0;
		
	}
	
	public int SuccessMessageBox() {
		AlertDialog.Builder alt_bld = new AlertDialog.Builder(this);
		alt_bld.setMessage(getText(R.string.successmsg));
		alt_bld.setCancelable(false);
		alt_bld.setPositiveButton("OK", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {
				
	
		}
		});	
		
		AlertDialog alert = alt_bld.create();
		// Title for AlertDialog
		alert.setTitle(getText(R.string.successtitle));
		// Icon for AlertDialog
		alert.setIcon(R.drawable.info48);
		//alert.setIcon(R.drawable.icon);
		alert.show();				
		return 0;		
	}
	
	public int CalcParts(int Csize){
		FileParts.setText("File parts being created: "+Csize);
		Csize = Csize+1;
		return Csize;
	}
	
	
	
	class ChunkValue {
        public ChunkValue( String spinnerText, int value ) {
            this.spinnerText = spinnerText;
            this.value = value;
        }

        public String getSpinnerText() {
            return spinnerText;
        }

        public int getValue() {
            return value;
        }

        @Override
		public String toString() {
            return spinnerText;
        }

        String spinnerText;
        int value;
    }
	public class SplitFileTask extends AsyncTask<String, String, String> {
		@Override
		protected String doInBackground(String... params) {
			FileInputStream fis = null;
    		File source = new File(params[0]);
			String sourceFName = source.getName(); // Get file name
            long sourceFSize = source.length(); // Get file size
            int PartSize =  Integer.parseInt(params[1]);
			int FileCount = (int) (sourceFSize / PartSize );
            if (sourceFSize % PartSize != 0) {
            	++FileCount;
            }           
            
            try {
				fis = new FileInputStream(source);
				int size = PartSize;
	            byte buffer[] = new byte[size];
	            int count = 1; // 0 files: we're beginning right now
	
	            PrintWriter UnsplitBat=new PrintWriter(new FileWriter(new File(params[2]+"UNSPLIT.BAT")));
	            PrintWriter UnsplitSh=new PrintWriter(new FileWriter(new File(params[2]+"unsplit.sh")));
	            PrintWriter Readme=new PrintWriter(new FileWriter(new File(params[2]+"Readme.txt")));
	            
	            String ReadmeText = (String) getText(R.string.readme1);
	            Readme.write(ReadmeText);
	            Readme.println();
	            
	            ReadmeText = (String) getText(R.string.readme2);
	            Readme.write(ReadmeText);
	            Readme.println();	            
	            Readme.write(" ");
	            Readme.println();	   
	            ReadmeText = (String) getText(R.string.readme3);
	            Readme.write(ReadmeText);
	            Readme.println();
	            ReadmeText = (String) getText(R.string.readme4);
	            Readme.write(ReadmeText);
	            Readme.println();
	            ReadmeText = (String) getText(R.string.readme5);
	            Readme.write(ReadmeText);
	            Readme.println();
	            ReadmeText = getText(R.string.readme6)+" "+MD5File;
	            Readme.write(ReadmeText);
	            Readme.println();	            
	            Readme.write(" ");
	            Readme.println();
	            ReadmeText = (String) getText(R.string.readme7);
	            Readme.write(ReadmeText);
	            Readme.println();
	            Readme.flush();
	            Readme.close();
	            
	            //String DestFilename;
                String destpath=params[2];				
	            //DestFilename=destpath+sourceFName+".zsp";
	            
                // pFilename
	            String pFilename=sourceFName+".zsp";
	            ZSPFilename=destpath+pFilename;
	            // sFilename
	            String sFilename=pFilename;
	            
	            UnsplitBat.write("echo File split with Cutter by Wininizio.it Software");
	            UnsplitBat.println();
	            UnsplitBat.write("echo http://cutter.zipgenius.com");
	            UnsplitBat.println();
	            UnsplitBat.write("echo -------------------------------------------------");
	            UnsplitBat.println();
	            
	            UnsplitSh.write("echo \"File split with Cutter by Wininizio.it Software\"");
	            UnsplitSh.println();
	            UnsplitSh.write("echo \"http://cutter.zipgenius.com\"");
	            UnsplitSh.println();
	            UnsplitSh.write("echo \"-------------------------------------------------\"");
	            UnsplitSh.println();
	            String shs="cat ";
	            while (true) {
	            	int i = fis.read(buffer, 0, size);
	                if (i == -1) break;

	                // Let's create the single file part
	                FileOutputStream fos = new FileOutputStream(destpath+sFilename);
	                fos.write(buffer, 0, i);
	                fos.flush();
	                fos.close();
	                if ((count+1)<=Integer.parseInt(params[1])) {
	                	UnsplitBat.write("copy /b \""+pFilename+"\"+\""+sFilename+"\" \""+sourceFName+"\"");
	                	UnsplitBat.println();
	                }
	                
	                pFilename=sourceFName;
	                shs=shs+sFilename+" ";
	                sFilename=sourceFName+"."+count;
	                //DestFilename=destpath+sourceFName+"."+count;
	                ++count; // Increment our file counter
	                pd.setProgress(count);
	            }
	            UnsplitBat.write("exit");
	            UnsplitBat.println();
	            UnsplitBat.flush();
	            UnsplitBat.close();
	            
	            UnsplitSh.write(shs);	            
	            UnsplitSh.println();
	            UnsplitSh.flush();
	            UnsplitSh.close();
	            
			} catch (FileNotFoundException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			return null;
   	}
		@Override		
		protected void onProgressUpdate(String... values) {
	         // aggiorno la progress dialog
	         //pd.incrementProgressBy(1);
			//pd.setMessage(values[0]);
	      }

	      @Override
	      protected void onPostExecute(String result) {
	         // chiudo la progress dialog
	         pd.dismiss();
	         SplitDone=true;
	         TextView menuhint = (TextView) findViewById(R.id.pressmenuline);
	         menuhint.setVisibility(View.VISIBLE);
	         SuccessMessageBox();
	      }

		
    }
	private class SendMail extends AsyncTask<String, String, String> {
		
		@Override
		protected String doInBackground(String... params) {
				
			
			// Get system properties
		    Properties props = System.getProperties();

		    // Setup mail server
		    /*  Host:='mail.zipgenius.it';
          AuthType:=smtpAuthLogin;
          Username:='cutter+cutter.zipgenius.it';
          Password:='cutter5_2010';
          Port:='25';
		    props.put("mail.smtp.host", "mail.zipgenius.it");
		    props.put("mail.smtp.user", "zginfo+zipgenius.it");
		    props.put("mail.smtp.password", "xevo250");*/
		    
		    props.put("mail.smtp.host", "mail.zipgenius.it");
		    props.put("mail.smtp.user", "cutter+cutter.zipgenius.it");
		    props.put("mail.smtp.password", "cutter5_2010");	
		    
		    // Loop
		    int c=0;
		    int pp = Integer.parseInt(params[1]);
		    int tot = pp;
		    // Get session
		    Session session;	
		    MimeMessage message;
		    String mestxt="";
		    mestxt=(String) getText(R.string.mailbody1);
		    mestxt=mestxt+ (String) getText(R.string.mailbody2);
		    mestxt=mestxt+ (String) getText(R.string.mailbody3);
		    mestxt=mestxt+ (String) getText(R.string.mailbody4);
		    mestxt=mestxt+ (String) getText(R.string.mailbody5);
		    
		    Formatter mailTXT = new Formatter();
		    String ffname=new File(params[0]).getName();
		    
		    mailTXT=mailTXT.format(mestxt, ffname, MD5File);
		    
		    // Get session
		    session = Session.getDefaultInstance(props, null);
		    // Define message
		    message = new MimeMessage(session);
		    
		    while (c<=pp) {	    	
			    // Define message
		    	try {
		    		session = Session.getDefaultInstance(props, null);
		    		message = new MimeMessage(session);

		    		message.setFrom(new InternetAddress(YourMail.toString(), YourName.toString()));
		    		message.addRecipient(Message.RecipientType.TO, new InternetAddress(DestMail.toString()));
		    		message.setSubject(new File(params[0]).getName()+" ("+Integer.toString(c+1)+"/"+tot+")");

		    		// Create the message part 
		    		BodyPart messageBodyPart = new MimeBodyPart();

		    		// Fill the message
		    		messageBodyPart.setText(mailTXT.toString());
		    				

		    		Multipart multipart = new MimeMultipart();
		    		multipart.addBodyPart(messageBodyPart);

		    		String filename = "";
		    		DataSource source;
		    		// Part two is attachment (FileManager-1.1.3.apk.zsp)
		    		messageBodyPart = new MimeBodyPart();
		    		if (c==0){
		    			filename = params[0]+".zsp";
		    		} else {
		    			filename = params[0]+"."+c;
		    		}
		    		File currfile = new File(filename);		    	
		    		
		    		source = new FileDataSource(filename);
		    		messageBodyPart.setDataHandler(new DataHandler(source));
		    		messageBodyPart.setFileName(source.getName());
		    		
		    		multipart.addBodyPart(messageBodyPart);
		    		
		    		if (c==0) {
		    			// Part two is attachment (FileManager-1.1.3.apk.zsp)
		    			messageBodyPart = new MimeBodyPart();
		    			filename = params[2]+"UNSPLIT.BAT";
		    			
		    			currfile = new File(filename);		    	
		    			source = new FileDataSource(filename);
		    			messageBodyPart.setDataHandler(new DataHandler(source));
		    			messageBodyPart.setFileName("UNSPLIT.TXT");
		    			multipart.addBodyPart(messageBodyPart);

		    			// Part two is attachment (FileManager-1.1.3.apk.zsp)
		    			messageBodyPart = new MimeBodyPart();
		    			filename = params[2]+"unsplit.sh";
		    			currfile = new File(filename);		    	
		    			source = new FileDataSource(filename);
		    			messageBodyPart.setDataHandler(new DataHandler(source));
		    			messageBodyPart.setFileName(source.getName());
		    			multipart.addBodyPart(messageBodyPart);

		    			// Part two is attachment (FileManager-1.1.3.apk.zsp)
		    			messageBodyPart = new MimeBodyPart();
		    			filename = params[2]+"Readme.txt";
		    			currfile = new File(filename);		    	
		    			source = new FileDataSource(filename);
		    			messageBodyPart.setDataHandler(new DataHandler(source));
		    			messageBodyPart.setFileName(source.getName());
		    			multipart.addBodyPart(messageBodyPart);
		    		} 
		    		
		    		// Put parts in message
		    		message.setContent(multipart);

		    		// Send the message
		    		Transport.send(message);
		    	} catch (Exception e) {
		    		
		    	}		    	
		    	c++;
		    	pd.setProgress(c);
		    }
		    
			return null;
   	}
		@Override		
		protected void onProgressUpdate(String... values) {
			//pd.setMessage(values[0]);
	      }

	      @Override
	      protected void onPostExecute(String result) {
	       
	         pd.dismiss();
	         //SuccessMessageBox();
	      }

		
    }
	private class MergeFileTask extends AsyncTask<String, String, String> {
		private String OFile; 
		
		@Override
		protected String doInBackground(String... params) {
			
			File inFile;
			File outFile;
			String inFN;
			inFN = params[0];
			String outFN = inFN;
			outFN = params[2];
			OFile = params[2];
			FileInputStream fileIS = null;
			outFile = new File(outFN);
			FileOutputStream fileOS;
			try {
				fileOS = new FileOutputStream(outFile);
				int c=0;
				boolean GoOn=true;
				while (GoOn){
					inFile= new File(inFN);					
					fileIS = new FileInputStream(inFN); 
					byte[] data = new byte[(int) inFile.length()];  
					int count = fileIS.read(data); 
					fileIS.close();
					fileOS.write(data,0,count); 
					fileOS.flush();
					publishProgress(inFN, Long.toString(inFile.length()), params[2]);	
					//Thread.sleep(2000);
					c++;
					inFN = outFN+"."+c;
					File NextFile = new File(inFN);
					if (NextFile.exists()==false) {
						GoOn=false;
						break;
					}
								
				}
				fileOS.close();
			} catch (Exception e) {
				
			};
			
			return null;
   	}
		@Override		
		protected void onProgressUpdate(String... values) {
			pd.setMessage(getText(R.string.testprogress));
	      }

	      @Override
	      protected void onPostExecute(String result) {
	       
	         pd.dismiss();
	         
			File oF = new File(OFile);
	         String getMD5 = "";	         
	         try {
				getMD5=splitfile.getMd5FileHash(oF);
			} catch (NoSuchAlgorithmException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	         if (MD5File.equals(getMD5)){
	        	 TestSuccessMessageBox();
	         } else {
	        	 FailMessageBox();
	         }
	         //deleteFile(OFile);
	        	 
	         //SuccessMessageBox();
	      }
	}
	
	public int TestSuccessMessageBox() {
		AlertDialog.Builder alt_bld = new AlertDialog.Builder(this);
		alt_bld.setMessage(getText(R.string.testrebuildok));
		alt_bld.setCancelable(false);
		alt_bld.setPositiveButton("OK", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {
				File ddF= new File(Destfile);
				ddF.delete();
			}
		});		
		
		AlertDialog alert = alt_bld.create();
		// Title for AlertDialog
		alert.setTitle(getText(R.string.successtitle));
		// Icon for AlertDialog
		alert.setIcon(R.drawable.info48);
		//alert.setIcon(R.drawable.icon);
		alert.show();				
		return 0;		
	}
	public int FailMessageBox() {
		AlertDialog.Builder alt_bld = new AlertDialog.Builder(this);
		alt_bld.setMessage(getText(R.string.testrebuildfail));
		alt_bld.setCancelable(false);
		alt_bld.setPositiveButton("OK", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {
				
			}
		});		
		
		AlertDialog alert = alt_bld.create();
		// Title for AlertDialog
		alert.setTitle(getText(R.string.errortitle));
		// Icon for AlertDialog
		alert.setIcon(R.drawable.close48);
		//alert.setIcon(R.drawable.icon);
		alert.show();				
		return 0;		
	}
	public static boolean deleteDir(File dir) {
        if (dir.isDirectory()) {
            String[] children = dir.list();
            for (int i=0; i<children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }
    
        // The directory is now empty so delete it
        return dir.delete();
    }
	public int RepeatSplitMessageBox() {
		AlertDialog.Builder alt_bld = new AlertDialog.Builder(this);
		alt_bld.setMessage(getText(R.string.warningmsg));
		alt_bld.setCancelable(false);
		alt_bld.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {
				File dDir = new File(Destfolder);
				if (deleteDir(dDir)) StartButton.setEnabled(true); 
				
			}
		});		
		alt_bld.setNegativeButton("No", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {
				
			}
		});
		
		AlertDialog alert = alt_bld.create();
		// Title for AlertDialog
		alert.setTitle(getText(R.string.warningtitle));
		// Icon for AlertDialog
		alert.setIcon(R.drawable.alert48);
		//alert.setIcon(R.drawable.icon);
		alert.show();				
		return 0;		
	}
}
 